const exportToExcel = (function () {
  // 编码要用utf-8不然默认gbk会出现中文乱码
  const uri = 'data:application/vnd.ms-excel;base64,',
    template =
      '<html xmlns:o="urn:schemas-microsoft-com:office:office" xmlns:x="urn:schemas-microsoft-com:office:excel" xmlns="http://www.w3.org/TR/REC-html40"><head><meta charset="UTF-8"><!--[if gte mso 9]><xml><x:ExcelWorkbook><x:ExcelWorksheets><x:ExcelWorksheet><x:Name>{worksheet}</x:Name><x:WorksheetOptions><x:DisplayGridlines/></x:WorksheetOptions></x:ExcelWorksheet></x:ExcelWorksheets></x:ExcelWorkbook></xml><![endif]--></head><body><span>{title}</span><table>{table}</table></html>'
  const base64 = function (s: any) {
    return window.btoa(unescape(encodeURIComponent(s)))
  }

  const format = (s: any, c: any) => {
    return s.replace(/{(\w+)}/g, (m: any, p: any) => {
      return Object.hasOwnProperty.call(c, p) ? c[p] : ''
    })
  }

  return (table: any, name: any, restArg: any) => {
    const ctx = {
      worksheet: name,
      table,
      ...restArg,
    }

    const url = uri + base64(format(template, ctx))

    if (navigator.userAgent.indexOf('Firefox') > -1) {
      window.location.href = url
    } else {
      const aLink = document.createElement('a')
      aLink.href = url
      aLink.download = name || ''
      let event
      if (window.MouseEvent) {
        event = new MouseEvent('click')
      } else {
        event = document.createEvent('MouseEvents')
        event.initMouseEvent('click', true, false, window, 0, 0, 0, 0, 0, false, false, false, false, 0, null)
      }
      aLink.dispatchEvent(event)
    }
  }
})()

// 导出函数
const ExportExcel = (column: any, data: any, excelName: any, restArg = {}) => {
  const typeMap = {
    image: getImageHtml,
    text: getTextHtml,
  }

  let thead = column.reduce((result: any, item: any, index: number) => {
    const keyLength = item.key.split(',').length
    if (keyLength > 1 && item.type === 'image') {
      result += `<th style="height:40px;" colspan="${keyLength}">${item.name}</th>`
    } else {
      result += `<th style="background-color: ${item.bgColor};">${item.name}</th>`
    }
    return result
  }, '')

  thead = `<thead><tr>${thead}</tr></thead>`
  let tbody = data.reduce((result: any, row: any) => {
    const temp = column.reduce((tds: any, col: any) => {
      const val = row[col.key]
      tds += typeMap[col.type || 'text'](val, col)
      return tds
    }, '')
    result += `<tr>${temp}</tr>`
    return result
  }, '')

  tbody = `<tbody>${tbody}</tbody>`

  const table = thead + tbody

  // 导出表格
  exportToExcel(table, excelName, restArg)

  function getTextHtml(val: any, options: any) {
    const bg = options.bg ? options.bg : 'transparent'
    return `<td style="text-align: center;border:1px solid ${bg}">${val}</td>`
  }

  function getImageHtml(val: string, options: any) {
    options = Object.assign({ width: 60 }, options)
    const urls = val.split(',')
    const keyList = options.key.split(',')
    let imageHtml = ''
    for (const index in keyList) {
      const imgurl = urls[index]
      if (!imgurl) {
        imageHtml += `<td style="width: ${options.width}px; height: ${options.height}px;"></td>`
      } else {
        if (options.height) {
          imageHtml += `<td style="width: ${options.width}px; height: ${options.height}px;"><img src="${imgurl}" width=${options.width} height=${options.height} /></td>`
        } else {
          imageHtml += `<td style="width: ${options.width}px; height: 120px;"><img src="${imgurl}" width=${options.width} /></td>`
        }
      }
    }

    return imageHtml
  }
}

export default ExportExcel
